﻿using Microsoft.AspNetCore.Authorization;
using RBACDemo.Ability.Docking.UserApp;
using RBACDemo.Ability.Docking.UserApp.Dtos;
using RBACDemo.Domain.Managers;
using RBACDemo.Domain.UserInfo;
using Youshow.Ace.Ability;
using Youshow.Ace.AspNetCore.ApiRouteDescription;
using Youshow.Ace.AspNetCore.ApiRouteDescription.Models;
using Youshow.Ace.AspNetCore.Jwt;

namespace RBACDemo.Ability.UserApp;

[Authorize(AceJwtPolicyDefault.AUTHORIZATION_POLICY)]
public class UserService(
    UserManager userManager,
    IAceApiRouteDescriptor aceApiRouteDescriptor,
    RoleAuthManager roleAuthManager) : AbilityServicer,IUserService
{
    /// <summary>
    ///  获取用户信息的同时获取其角色信息，获取角色信息的同时获取其权限信息
    /// </summary>
    /// <param name="ids">用户Id集合</param>
    /// <returns></returns>
    public async Task<List<UserDto>> GetUsersAsync(params long[] ids)
    {
        var resUsers = await userManager.GetUserAsync(ids);
        if (resUsers.Count == 1)
        {
            var resUser = resUsers.FirstOrDefault();
            resUser.Roles = await roleAuthManager.GetApiAuthToRoleAsync(resUser.Roles.ToArray());
        }
        else if (resUsers.Count > 1)
        {
            List<Role> rolesOfWillAddApiAuth = new();
            // 获取所有用户的所有角色
            var rolesOfUsers = resUsers.Select(m => m.Roles);
            // 把所有角色都加到rolesOfWillAddApiAuth集合中并去重
            foreach (var rolesOfUser in rolesOfUsers)
            {
                rolesOfWillAddApiAuth.AddRange(rolesOfUser);
            }

            rolesOfWillAddApiAuth = rolesOfWillAddApiAuth.DistinctBy(m => m.Id).ToList();
            // 根据所有roles去获取他们所属的ApiAuth
            var resRoles = await roleAuthManager.GetApiAuthToRoleAsync(rolesOfWillAddApiAuth.ToArray());

            // 循环每一个用户，并且添加Roles
            resUsers.ForEach(u =>
            {
                var roleIds = u.Roles.Select(m => m.Id);
                u.Roles = resRoles.FindAll(m => roleIds.Contains(m.Id));
            });
        }

        var userDtos = ModelMapper.Map<List<User>, List<UserDto>>(resUsers);

        return UserDto.SetApiAuths(userDtos);
    }

    /// <summary>
    ///  获取项目所有Service和Controller信息
    /// </summary>
    /// <returns></returns>
    public async Task<List<ApiRouteDescriptionModel>> GetApiRoutesAsync()
    {
        return aceApiRouteDescriptor.GetApiRouteDescriptions();
    }

    /// <summary>
    ///  根据userId、roleIds给用户添加相应的角色，保存在UserRoleMapping表中
    /// </summary>
    /// <param name="userId">用户Id</param>
    /// <param name="roleIds">角色Id集合</param>
    public async Task AddUserRolesAsync(long userId, params long[] roleIds)
    {
        await userManager.DeleteUserRoleAsync(userId);
        await userManager.AddUserRoleAsync(userId, roleIds.ToList());
    }
}